package com.dayuanit.dy17.atm.interceptor;

import com.alibaba.fastjson.JSON;
import com.dayuanit.dy17.atm.config.AtmPropertiesConfig;
import com.dayuanit.dy17.atm.dto.ResponseDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    public LoginInterceptor() {
        System.out.println("--------LoginInterceptor()------------");
    }

    /**
     * DispatcherServlet在调用controller之前，先调用preHander方法。
     * 如果返回true，则放行；反之，直接响应。
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("-------------LoginInterceptor pre------------------");
        System.out.println("requestURI=" + requestURI);

        //校验是否登录
        Object user = request.getSession().getAttribute("loginUser");
        if (null != user) {
            return true;
        }

        //木有登录 则返回登录页面 但要区分异步和同步
        String ajaxFlag = request.getHeader("X-Requested-With");
        if (StringUtils.isBlank(ajaxFlag)) {
            response.sendRedirect("/user/toLogin.do");
        } else {
            response.setContentType("application/json;charset=utf-8");
            response.getOutputStream().write(JSON.toJSONString(ResponseDTO.reLogin()).getBytes("UTF-8"));
        }
        return false;
    }
}
